Last updated: February 9 Tuesday 2021

Dynamically import a method in a file, from a string

from importlib import import_module
my_module = 'django.contrib.sessions.backends.cache.SessionStore'
import_module(my_module)

Check file exists or not

from os import path
path = '/xx/xx'
path.exists(path) # will return True/False

Inspecting current function

import inspect
from pprint import pprint
pprint(inspect.currentframe().f_locals)

Getting datetime in UTC format

from datetime import datetime, timezone
int(datetime.now(timezone.utc).timestamp())
### output will be like this
1603848107

Adding/Subracting timedelta

from datetime import datetime, timedelta
current = datetime.now()
# You can just skip others whose value is `0`
delta = timedelta(days=0, seconds=5, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
five_second_plus_current = current + delta

Printing very large numbers (python3)

one_hundred_thousand = 100_000
one_million = 1_000_000
total = one_hundred_thousand + one_million
# using fstring
print(f'{total:,}')

Using context managers for managing resources (like files, database connections)

with open('test.txt', 'r') as f:
file_content = f.read()
words = file_content.split(' ')
word_count = len(words)
print(word_count)

Usiing enumerate function

names = ['Corey', 'Ali', 'John', 'David']
for index, name in enumerate(names):
print(index, name)
# if you want to print index value starting from 1 you can do
for index, name in enumerate(names, start=1):
print(index, name)
# in this way you will get all the values but their numbering will start from 1

Using zip function

names = ['Peter parker', 'Barry', 'Klark']
heroes = ['Spider man', 'Flash', 'Superman']
for name, hero in zip(names, heroes):
print('f{name} is {hero}')
# that loop will iterate to the length of that list which is smaller

Using _ for unused variables

a, _ = (1,2)
print(a)

Doing unpacking the tuple / list

a, b, c = (1, 2, 3, 4)
# would give an error
# the correct one
a, b, *c = (1, 2, 3, 4)
# or
a, b, *_ = (1, 2, 3, 4)
# the following syntax will also work
a, b, *c, d = (1, 2, 3, 4, 5)
print(a)
print(b)
print(c)
print(d)
# in this case the output will be
1
2
[3, 4]
5

Using setattr and getattr method

class Person():
pass
person = Person()
perosn_info = {'first': 'Corey', 'last': 'Anderson'}
for key, value in person_info.items():
setattr(person, key, value)
for key in person_info.keys():
print(getattr(person, key))

Getting secret info like password from terminal

from getpass import getpass
name = input('Enter your name: ')
password = getpass('Enter your password: ')
print('Logging in ....')

Using -m to run the python modules that exist in the directory listed in sys.PATH

python -m my_module

Using help() function to get help

import smtpd
help(smtpd)

Using dir() function to list down all the attributes and functions

from datetime import datetime
dir(datetime)

Using lambda function

lmbda functions
lmbda2
lmbda3

Using map function


Using filter function


Using reduce function


Using displayhook to format your output

You can simply format your output just using the displayhook property available in sys module
It will work only in Python Interactive Mode. It will not change the functionality of print function

import sys
def my_display(x):
print('We are going to display output: ')
print(x)
sys.displayhook = my_display
x = 92
x
# output will be
We are going to display output
92

Redirections